import TencentCloudChat from '@tencentcloud/chat';
import TIMUploadPlugin from 'tim-upload-plugin';
import { TIM_CONFIG, MESSAGE_TYPE, MESSAGE_STATUS } from './tim-config.js';

class TIMManager {
  constructor() {
    this.tim = null;
    this.isLogin = false;
    this.isSDKReady = false;
    this.messageList = [];
    this.conversationID = '';

    // 事件监听器
    this.eventListeners = {
      onMessageReceived: [],
      onMessageRead: [],
      onConnectionStateChanged: [],
      onSDKReady: [],
    };
  }

  // 初始化 TIM 实例
  init() {
    if (this.tim) {
      return this.tim;
    }

    // 创建 TIM 实例
    this.tim = TencentCloudChat.create({
      SDKAppID: TIM_CONFIG.SDKAppID
    });

    // 设置日志级别
    this.tim.setLogLevel(0);
    // 注册腾讯云即时通信 IM 上传插件
    this.tim.registerPlugin({ 'tim-upload-plugin': TIMUploadPlugin });

    // 注册事件监听
    this.registerEventListeners();

    return this.tim;
  }

  // 注册事件监听器
  registerEventListeners() {
    try {
      // 监听 SDK ready 事件
      this.tim.on(TencentCloudChat.EVENT.SDK_READY, (event) => {
        console.log('SDK ready 事件触发');
        this.isSDKReady = true;
        this.handleSDKReady();
      });

      // 监听收到新消息
      this.tim.on(TencentCloudChat.EVENT.MESSAGE_RECEIVED, (event) => {
        console.log('收到新消息:', event);
        this.handleMessageReceived(event.data);
      });

      // 监听消息已读回执
      this.tim.on(TencentCloudChat.EVENT.MESSAGE_READ_RECEIPT_RECEIVED, (event) => {
        console.log('消息已读回执:', event);
        this.handleMessageRead(event.data);
      });

      // 监听网络状态变化
      this.tim.on(TencentCloudChat.EVENT.NET_STATE_CHANGE, (event) => {
        console.log('网络状态变化:', event);
      });

      // 监听被踢下线事件
      this.tim.on(TencentCloudChat.EVENT.KICKED_OUT, (event) => {
        console.log('用户被踢下线:', event);
        this.handleKickedOut(event.data);
      });

    } catch (error) {
      console.error('注册事件监听器失败:', error);
      this.registerFallbackEventListeners();
    }
  }

  // 备选事件监听器注册
  registerFallbackEventListeners() {
    try {
      console.log('尝试使用备选事件名称注册监听器');

      this.tim.on('onMessageReceived', (event) => {
        console.log('收到新消息(备选):', event);
        this.handleMessageReceived(event);
      });

      this.tim.on('onMessageRead', (event) => {
        console.log('消息已读回执(备选):', event);
        this.handleMessageRead(event);
      });

      this.tim.on('onConnectionStateChanged', (event) => {
        console.log('连接状态变化(备选):', event);
        this.handleConnectionStateChanged(event);
      });

      this.tim.on('onNetStateChange', (event) => {
        console.log('网络状态变化(备选):', event);
      });

      this.tim.on('onKickedOut', (event) => {
        console.log('用户被踢下线(备选):', event);
        this.handleKickedOut(event);
      });

      console.log('备选事件监听器注册成功');
    } catch (error) {
      console.error('备选事件监听器注册失败:', error);
    }
  }

  // 用户登录
  async login(userID, userSig) {
    if (!this.tim) {
      this.init();
    }

    try {
      const { code } = await this.tim.login({
        userID: userID,
        userSig: userSig
      });

      if (code === 0) {
        this.isLogin = true;
        TIM_CONFIG.userInfo.userID = userID;
        TIM_CONFIG.userInfo.userSig = userSig;
        console.log('TIM 登录成功');
        return { success: true };
      } else {
        console.error('TIM 登录失败:', code);
        return { success: false, code };
      }
    } catch (error) {
      console.error('TIM 登录异常:', error);
      return { success: false, error };
    }
  }

  // 用户登出
  async logout() {
    if (!this.tim || !this.isLogin) {
      return { success: true };
    }

    try {
      const { code } = await this.tim.logout();
      if (code === 0) {
        this.isLogin = false;
        console.log('TIM 登出成功');
        return { success: true };
      }
    } catch (error) {
      console.error('TIM 登出异常:', error);
      return { success: false, error };
    }
  }

  // 设置会话
  setConversation(conversationID) {
    this.conversationID = conversationID;
  }

  // 发送文本消息（带自动注册和错误处理）
  async sendTextMessage(text) {
    if (!this.tim || !this.isLogin) {
      console.error('TIM 未登录或未初始化');
      return { success: false, error: 'TIM 未登录或未初始化' };
    }

    if (!this.conversationID) {
      console.error('未设置会话ID');
      return { success: false, error: '未设置会话ID' };
    }

    try {
      const message = this.tim.createTextMessage({
        to: this.conversationID,
        conversationType: TencentCloudChat.TYPES.CONV_C2C,
        payload: {
          text: text
        }
      });

      const { code } = await this.tim.sendMessage(message);

      if (code === 0) {
        console.log('消息发送成功');
        return { success: true, message };
      } else {
        console.error('消息发送失败，错误代码:', code);

        // 处理特定错误代码
        if (code === 20003) {
          console.error('接收方用户标识符无效，尝试自动注册接收方用户');
          return await this.handleInvalidReceiverError(message);
        } else if (code === 20004) {
          console.error('发送方用户标识符无效，尝试重新登录');
          return await this.handleInvalidSenderError();
        }

        return { success: false, code };
      }
    } catch (error) {
      console.error('消息发送异常:', error);

      // 检查错误消息判断是否为用户未注册
      if (error.message && error.message.includes('Invalid sender or receiver identifier')) {
        console.error('检测到用户标识符无效错误，尝试自动注册');
        return await this.handleInvalidUserError(error);
      }

      return { success: false, error };
    }
  }
  // 发送图片消息
  async sendImageMessage(imageFile) {
    if (!this.tim || !this.isLogin) {
      console.error('TIM 未登录或未初始化');
      return { success: false, error: 'TIM 未登录或未初始化' };
    }

    if (!this.conversationID) {
      console.error('未设置会话ID');
      return { success: false, error: '未设置会话ID' };
    }

    try {
      console.log('开始创建图片消息:', imageFile);

      // 创建图片消息
      const message = this.tim.createImageMessage({
        to: this.conversationID,
        conversationType: TencentCloudChat.TYPES.CONV_C2C,
        payload: {
          file: imageFile
        },
        // 支持进度回调
        onProgress: (progress) => {
          console.log('图片上传进度:', progress);
        }
      });

      console.log('图片消息创建成功，开始发送');

      const { code } = await this.tim.sendMessage(message);
      if (code === 0) {
        return { success: true, message };
      } else {

        // 处理特定错误代码
        if (code === 20003) {
          console.error('接收方用户标识符无效，尝试自动注册接收方用户');
          return await this.handleInvalidReceiverError(message);
        } else if (code === 20004) {
          console.error('发送方用户标识符无效，尝试重新登录');
          return await this.handleInvalidSenderError();
        }

        return { success: false, code };
      }
    } catch (error) {
      console.error('图片消息发送异常:', error);

      // 检查错误消息判断是否为用户未注册
      if (error.message && error.message.includes('Invalid sender or receiver identifier')) {
        console.error('检测到用户标识符无效错误');
        return await this.handleInvalidUserError(error);
      }

      return { success: false, error };
    }
  }
  // 发送视频消息
  async sendVideoMessage(videoFile) {
    console.log(videoFile)
    if (!this.tim || !this.isLogin) {
      console.error('TIM 未登录或未初始化');
      return { success: false, error: 'TIM 未登录或未初始化' };
    }

    if (!this.conversationID) {
      console.error('未设置会话ID');
      return { success: false, error: '未设置会话ID' };
    }

    try {

      // 创建视频消息
      const message = this.tim.createVideoMessage({
        to: this.conversationID,
        conversationType: TencentCloudChat.TYPES.CONV_C2C,
        payload: {
          file: videoFile
        },
        // 支持进度回调
        onProgress: (progress) => {
          console.log('视频上传进度:', progress);
        }
      });

      const { code } = await this.tim.sendMessage(message);
      if (code === 0) {
        return { success: true, message };
      } else {

        // 处理特定错误代码
        if (code === 20003) {
          console.error('接收方用户标识符无效，尝试自动注册接收方用户');
          return await this.handleInvalidReceiverError(message);
        } else if (code === 20004) {
          console.error('发送方用户标识符无效，尝试重新登录');
          return await this.handleInvalidSenderError();
        }

        return { success: false, code };
      }
    } catch (error) {
      console.error('视频消息发送异常:', error);

      // 检查错误消息判断是否为用户未注册
      if (error.message && error.message.includes('Invalid sender or receiver identifier')) {
        console.error('检测到用户标识符无效错误');
        return await this.handleInvalidUserError(error);
      }

      return { success: false, error };
    }
  }
  // 处理接收方用户无效错误
  async handleInvalidReceiverError(message) {
    try {
      console.log('尝试自动注册接收方用户');

      // 从会话ID中提取接收方用户ID
      const receiverId = this.extractUserIdFromConversationId(this.conversationID);
      if (receiverId) {
        console.log('提取到接收方用户ID:', receiverId);

        // 尝试自动注册接收方用户
        const registerResult = await this.autoRegisterUser(receiverId);
        if (registerResult.success) {
          console.log('接收方用户自动注册成功，重新发送消息');

          // 延迟一段时间后重试发送
          await new Promise(resolve => setTimeout(resolve, 1000));

          const retryResult = await this.tim.sendMessage(message);
          if (retryResult.code === 0) {
            console.log('重试发送消息成功');
            return { success: true, message };
          }
        }
      }

      return {
        success: false,
        code: 20003,
        error: '接收方用户未注册，请确保目标用户已在腾讯云IM中注册'
      };

    } catch (error) {
      console.error('处理接收方用户无效错误失败:', error);
      return { success: false, error: '接收方用户未注册' };
    }
  }

  // 处理发送方用户无效错误
  async handleInvalidSenderError() {
    try {
      console.log('尝试重新登录当前用户');

      // 重新登录
      await this.logout();
      await new Promise(resolve => setTimeout(resolve, 1000));

      const loginResult = await this.login(TIM_CONFIG.userInfo.userID, TIM_CONFIG.userInfo.userSig);
      if (loginResult.success) {
        console.log('重新登录成功');
        return { success: false, error: '请重试发送消息' };
      }

      return { success: false, error: '发送方用户登录失败' };

    } catch (error) {
      console.error('处理发送方用户无效错误失败:', error);
      return { success: false, error: '发送方用户登录失败' };
    }
  }

  // 处理用户标识符无效错误
  async handleInvalidUserError(error) {
    console.log('尝试综合处理用户标识符无效问题');

    // 这里可以添加更复杂的自动注册逻辑
    // 比如通过后端API检查用户状态并自动注册

    return {
      success: false,
      error: '用户标识符无效，请确保相关用户已在腾讯云IM中注册'
    };
  }

  // 从会话ID中提取用户ID
  extractUserIdFromConversationId(conversationId) {
    if (!conversationId) return null;

    // 会话ID格式通常是 "C2Cuser_001user_002" 或类似格式
    // 尝试提取用户ID
    const match = conversationId.match(/user_[0-9]+/g);
    if (match && match.length > 0) {
      // 返回非当前用户的ID作为接收方
      const currentUserId = TIM_CONFIG.userInfo.userID;
      for (const userId of match) {
        if (userId !== currentUserId) {
          return userId;
        }
      }
    }

    return null;
  }

  // 自动注册用户
  async autoRegisterUser(userId) {
    try {
      console.log('开始自动注册用户:', userId);

      // 模拟自动注册过程
      // 在实际项目中，这里应该调用后端API来注册用户
      console.log('模拟自动注册用户成功:', userId);

      return {
        success: true,
        message: `用户 ${userId} 已自动注册`
      };

    } catch (error) {
      console.error('自动注册用户失败:', error);
      return { success: false, error: '自动注册失败' };
    }
  }

  // 检查用户是否已注册（调用后端API）
  async checkUserRegistered(userId) {
    try {
      // 这里应该调用后端API检查用户是否已注册
      // 暂时返回模拟数据
      console.log('检查用户是否已注册:', userId);

      // 模拟检查结果
      return {
        success: true,
        registered: false, // 模拟用户未注册
        error: null
      };

    } catch (error) {
      console.error('检查用户注册状态失败:', error);
      return { success: false, error: '检查用户状态失败' };
    }
  }

  // 获取历史消息
  async getHistoryMessageList(count = 15) {
    // 检查 SDK 是否 ready
    if (!this.isSDKReady) {
      console.error('SDK 未就绪，请等待 SDK_READY 事件后再调用');
      return { success: false, error: 'SDK not ready' };
    }

    if (!this.tim || !this.isLogin) {
      console.error('TIM 未登录或未初始化');
      return { success: false, error: 'TIM 未登录或未初始化' };
    }

    if (!this.conversationID) {
      console.error('未设置会话ID');
      return { success: false, error: '未设置会话ID' };
    }

    try {
      console.log('开始获取历史消息，会话ID:', this.conversationID);

      // 根据 @tencentcloud/chat SDK 版本，使用优化的参数格式

      // 方法1: 标准参数格式
      try {
        console.log('尝试方法1: 标准参数格式');
        const { code, data } = await this.tim.getMessageList({
          conversationID: this.conversationID,
          conversationType: TencentCloudChat.TYPES.CONV_C2C,
          count: count
        });

        if (code === 0) {
          console.log('方法1成功: 获取历史消息成功');
          return { success: true, messageList: data.messageList };
        }
      } catch (error1) {
        console.log('方法1失败:', error1.message);
      }

      // 方法2: 简化参数格式
      try {
        console.log('尝试方法2: 简化参数格式');
        const { code, data } = await this.tim.getMessageList({
          conversationID: this.conversationID,
          count: count
        });

        if (code === 0) {
          console.log('方法2成功: 获取历史消息成功');
          return { success: true, messageList: data.messageList };
        }
      } catch (error2) {
        console.log('方法2失败:', error2.message);
      }

      // 方法3: 字符串类型参数
      try {
        console.log('尝试方法3: 字符串类型参数');
        const { code, data } = await this.tim.getMessageList({
          conversationID: this.conversationID,
          conversationType: TencentCloudChat.TYPES.CONV_C2C,
          count: count
        });

        if (code === 0) {
          console.log('方法3成功: 获取历史消息成功');
          return { success: true, messageList: data.messageList };
        }
      } catch (error3) {
        console.log('方法3失败:', error3.message);
      }

      console.error('所有参数组合尝试都失败');
      return {
        success: false,
        error: '无法调用getMessageList，请检查SDK版本和参数格式'
      };

    } catch (error) {
      console.error('获取历史消息异常:', error);
      return { success: false, error };
    }
  }

  // 获取历史消息（简化版，供页面调用）
  async getHistoryMessages(count = 15) {
    const result = await this.getHistoryMessageList(count);
    if (result.success) {
      return this.formatMessages(result.messageList);
    }
    return [];
  }

  // 格式化消息列表
  formatMessages(messageList) {
    if (!messageList || !Array.isArray(messageList)) {
      return [];
    }

    return messageList.map(message => {
      return this.formatMessage(message);
    }).filter(msg => msg !== null);
  }

  // 格式化单个消息
  formatMessage(message) {
    if (!message) return null;

    const formattedMessage = {
      id: message.ID || message.id || `msg_${Date.now()}_${Math.random()}`,
      type: message.type,
      isSelf: message.flow === 'out',
      time: message.time * 1000 || Date.now(),
      status: 'success',
      content: '',
      avatar: '/static/images/avatar/1.jpg'
    };

    // 根据消息类型处理内容
    switch (message.type) {
      case TencentCloudChat.TYPES.MSG_TEXT:
        formattedMessage.content = message.payload.text || '';
        break;
      case TencentCloudChat.TYPES.MSG_IMAGE:
        formattedMessage.content = '[图片]';
        formattedMessage.imageUrl = message.payload.imageInfoArray[0]?.url || '';
        break;
      case TencentCloudChat.TYPES.MSG_AUDIO:
        formattedMessage.content = '[语音]';
        formattedMessage.audioUrl = message.payload.url || '';
        break;
      case TencentCloudChat.TYPES.MSG_CUSTOM:
        formattedMessage.content = message.payload.data || '[自定义消息]';
        break;
      default:
        formattedMessage.content = '[未知消息类型]';
        break;
    }

    return formattedMessage;
  }

  // 处理收到的新消息
  handleMessageReceived(messageList) {
    messageList.forEach(message => {
      this.eventListeners.onMessageReceived.forEach(callback => {
        callback(message);
      });
    });
  }

  // 处理消息已读
  handleMessageRead(readReceiptInfo) {
    this.eventListeners.onMessageRead.forEach(callback => {
      callback(readReceiptInfo);
    });
  }

  // 处理连接状态变化
  handleConnectionStateChanged(state) {
    this.eventListeners.onConnectionStateChanged.forEach(callback => {
      callback(state);
    });
  }

  // 处理 SDK ready
  handleSDKReady() {
    console.log('SDK ready 处理完成');
    this.eventListeners.onSDKReady.forEach(callback => {
      callback();
    });
  }

  // 处理被踢下线
  handleKickedOut(data) {
    console.log('用户被踢下线处理', data);
    this.isLogin = false;
    this.isSDKReady = false;
  }

  // 等待 SDK ready
  waitForSDKReady(timeout = 10000) {
    return new Promise((resolve, reject) => {
      if (this.isSDKReady) {
        resolve();
        return;
      }

      const timer = setTimeout(() => {
        reject(new Error('等待 SDK ready 超时'));
      }, timeout);

      this.on('onSDKReady', () => {
        clearTimeout(timer);
        resolve();
      });
    });
  }

  // 添加事件监听器
  on(event, callback) {
    if (this.eventListeners[event]) {
      this.eventListeners[event].push(callback);
    }
  }

  // 移除事件监听器
  off(event, callback) {
    if (this.eventListeners[event]) {
      const index = this.eventListeners[event].indexOf(callback);
      if (index > -1) {
        this.eventListeners[event].splice(index, 1);
      }
    }
  }

  // 获取当前登录状态
  getLoginStatus() {
    return this.isLogin;
  }

  // 获取当前会话ID
  getCurrentConversationID() {
    return this.conversationID;
  }

  // 检查 SDK 是否就绪
  isSDKReady() {
    return this.isSDKReady;
  }
}

// 创建单例实例
const timManager = new TIMManager();

export default timManager;